// router/router.js
const Router = require("koa-router");
const swaggerJsDoc = require("swagger-jsdoc");
const swaggerUi = require("swagger-ui-koa");
const config = require("../config");
const { router: userRouter } = require("./user/userRouter");
const { router: townRouter } = require("./town/townRouter");
const { router: articleRouter } = require("./article");
const { router: merchantRouter } = require("./merchan");

// 配置接口文档
const swaggerOptions = {
  swaggerDefinition: {
    openapi: "3.0.0",
    info: {
      title: "Nfu Town API",
      version: "2.0.0",
      description: "Koa API documentation",
    },
    servers: [
      {
        url: `http://${config.apiDocumentIp}:${config.apiDocumentPort}`, // 远端服务器
        description:
          "Remote server with API documentation available at specified IP and port",
      },
      {
        url: `http://127.0.0.1:8002`, // 本地服务器
        description: "Local server running on port 8002 for development",
      },
      {
        url: `http://${config.serverIp}:${config.serverPort}`, // 本地服务器
        description: "Configured server accessible via specified IP and port",
      },
    ],
  },
  apis: ["./router/**/*.js"], // 需要处理的 API 文件路径
};
const swaggerDocs = swaggerJsDoc(swaggerOptions);

// 创建接口路由
const router = new Router();

// 设置示例接口
/**
 * @swagger
 * /example:
 *   get:
 *     summary: 示例接口
 *     description: 返回 "Hello, World!" 示例响应
 *     responses:
 *       200:
 *         description: 请求成功，返回示例消息
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: Hello, World!
 */
router.get("/example", async (ctx) => {
  ctx.body = { message: "Hello, World!" };
});

// 设置文档接口
/**
 * @swagger
 * /api-docs:
 *   get:
 *     summary: 获取 API 文档页面
 *     description: 提供 Swagger UI 页面，用于查看和测试 API 文档。
 *     responses:
 *       200:
 *         description: 成功返回 Swagger UI 页面
 *         content:
 *           text/html:
 *             schema:
 *               type: string
 *               example: "<!DOCTYPE html><html>...</html>"
 */
router.get("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocs));

// 设置项目接口
router.use(
  "/users", // users 前缀
  userRouter.routes(),
  userRouter.allowedMethods(),
); // 用户接口
router.use(
  "/towns", // towns 前缀
  townRouter.routes(),
  townRouter.allowedMethods(),
); // 小镇接口
router.use(
  "/merchants", // merchants 前缀
  merchantRouter.routes(),
  merchantRouter.allowedMethods(),
); // 商店接口
router.use(
  "/articles", // articles 前缀
  articleRouter.routes(),
  articleRouter.allowedMethods(),
); // 文章接口

// 导出所有路由
module.exports = router;
